package api

import (
	admindao "TaskAssignmentSystem/internal/admin/dao"
	admin "TaskAssignmentSystem/internal/admin/services"
	team "TaskAssignmentSystem/internal/admin/services"
	"TaskAssignmentSystem/internal/app/dao"
	"TaskAssignmentSystem/internal/app/services"
	"TaskAssignmentSystem/internal/pkg/middleware/handler"
	"TaskAssignmentSystem/pkg/db/mysql"
	"TaskAssignmentSystem/pkg/oss"
	"TaskAssignmentSystem/pkg/timehandler"
	"TaskAssignmentSystem/pkg/utils"
	"errors"
	"fmt"
	"github.com/go-the-way/exl"
	"github.com/kataras/iris/v12"
	"github.com/xuri/excelize/v2"
	"gorm.io/gorm"
	"io/ioutil"
	"os"
	"strconv"
	"time"
)

const (
	IS_EFFECTIVE_MANPOWER_FALSE = "0" //是否有效人力-否
	IS_EFFECTIVE_MANPOWER_TRUE  = "1" //是否有效人力-是
)

func init() {
	go RegisterTeam()
}

func RegisterTeam() {
	for {
		if user, ok := <-services.SystemUserTeamChan; ok {
			fmt.Printf("RegisterTeam %s name %s", user.TeamNumber, user.RealName)
			var teamServe admin.TeamService
			teamServe.EffectiveManpower(user)
		}
	}
}

// 团队基础设置查询
func TeamProfileHandler(ctx iris.Context) {
	var dictServe services.SystemDictService
	if data, err := dictServe.GetValueByType(team.ZXZ_TEAM_PROFILE); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(data))
		return
	}
}

type EditTeamRequest struct {
	Id          uint   `json:"id" validate:"required"`
	Val         string `json:"val"`
	Number      uint   `json:"number"`
	Description string `json:"description"`
}

// 修改团队基础设置设置
func TeamProfileUpdateHandler(ctx iris.Context) {
	var RequestParams EditTeamRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var teamServe admin.TeamService
	var dictServe services.SystemDictService
	if res, err := dictServe.GetDictById(RequestParams.Id); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
	} else {
		if res.DictCode == team.ZXZ_TEAM_PROFILE_ALL || //团队功能（0-关闭，1-开启）
			res.DictCode == team.ZXZ_TEAM_PROFILE_ACTIVITY || //团队活动（0-关闭，1-开启）
			res.DictCode == team.ZXZ_TEAM_PROFILE_CREATE || //团队自主创建条件：历史芝草大于等于num
			res.DictCode == team.ZXZ_TEAM_PROFILE_CREATE_CONSUME || //团队创建消耗芝草
			res.DictCode == team.ZXZ_TEAM_PROFILE_AUTH_PEOPLE { //有效人数-完成实名认证（0-关闭，1-开启）
			if err := dictServe.UpdateValueAndNumber(RequestParams.Id, RequestParams.Number, ""); err != nil {
				ctx.JSON(utils.ResponseServerError(err))
				return
			} else {
				go teamServe.AllEffectiveManpower() //全量计算有效人数
				ctx.JSON(utils.ResponseOK())
				return
			}
		} else if res.DictCode == team.ZXZ_TEAM_PROFILE_AUTH_PEOPLE_CONSUME { //有效人数-历史芝草大于等于N （0-关闭，1-开启）
			_, err := strconv.Atoi(RequestParams.Val)
			if err != nil {
				ctx.JSON(utils.ResponseServerError(errors.New("有效人数必须是数字！")))
				return
			}
			if err := dictServe.UpdateValueAndNumber(RequestParams.Id, RequestParams.Number, RequestParams.Val); err != nil {
				ctx.JSON(utils.ResponseServerError(err))
				return
			} else {
				go teamServe.AllEffectiveManpower() //全量计算有效人数
				ctx.JSON(utils.ResponseOK())
				return
			}
		} else if res.DictCode == team.ZXZ_TEAM_PROFILE_ACTIVITY_TIME { // 活动范围时间
			startTime, err := time.ParseInLocation(timehandler.FormatLayoutTime, RequestParams.Val, time.Local)
			if err != nil {
				ctx.JSON(utils.ResponseServerError(errors.New("团队创建活动开始时间格式错误！")))
				return
			}
			endTime, err := time.ParseInLocation(timehandler.FormatLayoutTime, RequestParams.Description, time.Local)
			if err != nil {
				ctx.JSON(utils.ResponseServerError(errors.New("团队创建活动结束时间格式错误！")))
				return
			}
			if !startTime.Before(endTime) {
				ctx.JSON(utils.ResponseServerError(errors.New("团队创建活动结束时间需要大于开始时间！")))
				return
			}
			if err := dictServe.UpdateValueAndDescription(RequestParams.Id, RequestParams.Val, RequestParams.Description); err != nil {
				ctx.JSON(utils.ResponseServerError(err))
				return
			} else {
				go teamServe.AllEffectiveManpower() //全量计算有效人数
				ctx.JSON(utils.ResponseOK())
				return
			}
		} else {
			ctx.JSON(utils.ResponseServerError(errors.New("id对应编码错误！")))
			return
		}
	}
}

type ReadExcelEffectiveNumber struct {
	Level  string `excel:"团队等级（必填）"`
	Number int    `excel:"需要的累计有效人数（必填）"`
}

func (*ReadExcelEffectiveNumber) Configure(rc *exl.ReadConfig) {}

// 团队各等级要求有效人数导入
func ExcelEffectiveNumberImportsHandler(ctx iris.Context) {
	_, handle, err := ctx.FormFile("file")
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	file, _ := handle.Open()
	defer file.Close()
	if models, err := exl.Read[*ReadExcelEffectiveNumber](file); err != nil {
		fmt.Println("read excel err:" + err.Error())
		ctx.JSON(utils.ResponseServerError(errors.New("excel读取错误")))
		return
	} else {
		fmt.Printf("read excel num: %d\n", len(models))
		var dictServe services.SystemDictService
		var teamServe admin.TeamService
		var dictDao admindao.Common[dao.SystemDict]
		dictDao.DeleteByStringColumn("dict_type", "ZXZ_TEAM_LEVEL")
		for i, model := range models {
			//从第二行开始读取
			if i == 0 || utils.StringIsEmpty(model.Level) {
				continue
			}
			dictServe.DictTypeInsertOrUpdateNumber(team.ZXZ_TEAM_LEVEL, model.Level, model.Number)
		}
		go teamServe.AllEffectiveManpower() //全量计算有效人数
		ctx.JSON(utils.ResponseOK())
		return
	}
}

// 团队各等级要求有效人数查询
func EffectiveNumberHandler(ctx iris.Context) {
	var dictServe services.SystemDictService
	if data, err := dictServe.GetValueByType(team.ZXZ_TEAM_LEVEL); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(data))
		return
	}
}

type EditTeamNumberRequest struct {
	Id     uint `json:"id" validate:"required"`
	Number uint `json:"number"`
}

// 团队有效人数设置修改
func EffectiveNumberUpdateHandler(ctx iris.Context) {
	var RequestParams EditTeamNumberRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var dictServe services.SystemDictService
	if res, err := dictServe.GetDictById(RequestParams.Id); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
	} else {
		if res.DictType != team.ZXZ_TEAM_LEVEL {
			ctx.JSON(utils.ResponseServerError(errors.New("id类型不属于团队等级有效人数")))
			return
		}
		if err := dictServe.UpdateValueAndNumber(RequestParams.Id, RequestParams.Number, ""); err != nil {
			ctx.JSON(utils.ResponseServerError(err))
			return
		} else {
			var teamServe admin.TeamService
			go teamServe.AllUpdateEffectiveManpower() //全量计算团队等级
			ctx.JSON(utils.ResponseOK())
			return
		}
	}
}

type IncomeQueryRequest struct {
	Page     int64 `json:"page" validate:"required"`
	PageSize int64 `json:"page_size" validate:"required"`
}

type ReadExcelTeamIncomeSetting struct {
	ProjectId    string  `excel:"项目ID（必填）"`
	Title        string  `excel:"项目名称（选填）"`
	IncomeType   int     `excel:"提成形式（1表示基础工资，2表示固定数值）（必填）"`
	Level        int     `excel:"团队等级（必填）"`
	IncomeNumber float64 `excel:"提成比例（如果填写百分比，则是按照基础工资*百分比发放）（如果填写的是固定数值，则按照固定值*数量发放）（必填）"`
}

func (*ReadExcelTeamIncomeSetting) Configure(rc *exl.ReadConfig) {}

// 团队收益导入
func IncomeImportHandler(ctx iris.Context) {
	//1.解析execl
	_, handle, err := ctx.FormFile("file")
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	file, _ := handle.Open()
	defer file.Close()
	if models, err := exl.Read[*ReadExcelTeamIncomeSetting](file); err != nil {
		fmt.Println("read excel err:" + err.Error())
		ctx.JSON(utils.ResponseServerError(errors.New("excel读取错误")))
		return
	} else {
		fmt.Printf("read excel num: %d\n", len(models))
		teamIncomeSetting := make([]admindao.SystemTeamIncomeSetting, 0)
		for i, model := range models {
			//从第二行开始读取
			if i == 0 || utils.StringIsEmpty(model.ProjectId) {
				continue
			}
			//index := i - 1
			var teamIncome admindao.SystemTeamIncomeSetting
			teamIncome.ProjectId = model.ProjectId
			teamIncome.Title = model.Title
			teamIncome.IncomeType = model.IncomeType
			teamIncome.Level = model.Level
			teamIncome.IncomeNumber = model.IncomeNumber
			teamIncomeSetting = append(teamIncomeSetting, teamIncome)
		}
		var teamServe admin.TeamService
		if err := teamServe.BatchInsertTeamIncomeSetting(teamIncomeSetting); err != nil {
			ctx.JSON(utils.ResponseServerError(err))
			return
		} else {
			ctx.JSON(utils.ResponseOK())
		}
	}
}

// 团队收益查询
func IncomeHandler(ctx iris.Context) {
	var RequestParams IncomeQueryRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var teamServe admin.TeamService
	if total, list, err := teamServe.QueryTeamIncomeSetting(RequestParams.Page, RequestParams.PageSize); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(iris.Map{"count": total, "list": list}))
		return
	}
}

type IncomeUpdateRequest struct {
	Id           uint    `json:"id" validate:"required"` //设置id
	ProjectId    string  `json:"project_id"`             //项目id
	Title        string  `json:"title"`                  //项目名称
	IncomeType   int     `json:"income_type"`            //提成形式[1:基础工资,2:固定数值]
	Level        int     `json:"level"`                  //团队等级
	IncomeNumber float64 `json:"income_number"`          //提成
}

// 团队收益修改
func IncomeUpdateHandler(ctx iris.Context) {
	var RequestParams IncomeUpdateRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var teamServe admin.TeamService
	if err := teamServe.UpdateTeamIncomeSetting(RequestParams.Id, RequestParams.ProjectId, RequestParams.Title,
		RequestParams.IncomeType, RequestParams.Level, RequestParams.IncomeNumber); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseOK())
		return
	}
}

type CreateTeamRequest struct {
	UserId string `json:"userId" validate:"required"`
}

// 创建团队
func CreateTeamHandler(ctx iris.Context) {
	var RequestParams CreateTeamRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var teamServe admin.TeamService
	if err := teamServe.CreateTeam(RequestParams.UserId); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseOK())
		return
	}
}

func IsCreateTeamHandler(ctx iris.Context) {
	var RequestParams CreateTeamRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var teamServe admin.TeamService
	if teamServe.IsCreateTeam(RequestParams.UserId) {
		ctx.JSON(utils.ResponseData(map[string]interface{}{"flag": true}))
		return
	} else {
		ctx.JSON(utils.ResponseData(map[string]interface{}{"flag": false}))
		return
	}
}

type DeleteTeamRequest struct {
	TeamNumber string `json:"teamNumber" validate:"required"`
}

func TeamDeleteHandler(ctx iris.Context) {
	var RequestParams DeleteTeamRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var teamServe admin.TeamService
	if teamServe.DeleteTeam(RequestParams.TeamNumber) {
		ctx.JSON(utils.ResponseOK())
		return
	} else {
		ctx.JSON(utils.ResponseServerError(errors.New("团队不存在，或已被删除")))
		return
	}
}

type ReadExcelTeam struct {
	UserId          string `excel:"团长ID(必填)"`
	UserName        string `excel:"团长姓名(选填)"`
	TeamNumber      string `excel:"团队编号(选填)"`
	TeamPermissions string `excel:"团队项目ID资格（不填表示全部项目，可视规则按照项目配置决定；如果填写则表示只能看到填写的项目，可视规则由本表以及项目表共同决定）（必填）"`
}

func (*ReadExcelTeam) Configure(rc *exl.ReadConfig) {}
func TeamImportHandler(ctx iris.Context) {
	//1.解析execl
	_, handle, err := ctx.FormFile("file")
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	file, _ := handle.Open()
	defer file.Close()
	if models, err := exl.Read[*ReadExcelTeam](file); err != nil {
		fmt.Println("read excel err:" + err.Error())
		ctx.JSON(utils.ResponseServerError(errors.New("excel读取错误")))
		return
	} else {
		var userDao dao.Common[dao.SystemUser]
		fmt.Printf("read excel num: %d\n", len(models))
		teams := make([]admindao.SystemTeam, len(models)-1)
		var dictServe admin.SystemDictService
		for i, model := range models {
			//从第二行开始读取
			if i == 0 {
				continue
			}
			index := i - 1
			teams[index].UserId = model.UserId
			teams[index].UserName = model.UserName
			if utils.StringIsNotEmpty(model.TeamNumber) {
				teams[index].TeamNumber = model.TeamNumber
			} else {
				teams[index].TeamNumber, _ = dictServe.GetNextTeamNumber()
			}
			teams[index].TeamPermissions = model.TeamPermissions
			if user, err := userDao.First(map[string]interface{}{"user_id": model.UserId}); err == nil {
				teams[index].UserName = user.RealName
				teams[index].NickName = user.NickName
			}
		}
		var teamServe admin.TeamService
		if err := teamServe.BatchInsertTeam(teams); err != nil {
			ctx.JSON(utils.ResponseServerError(err))
			return
		} else {
			ctx.JSON(utils.ResponseOK())
		}
	}
}

type UpdateTeamReadExcel struct {
	UserID                 string `excel:"用户ID(必填)"`
	TeamNumber             string `excel:"修改到新团队(选填)"`
	IsEffectiveManpower    int    `excel:"强制修改为有效人数(选填)（如果已经是有效人数则不做任何改变）"`
	IsNotEffectiveManpower int    `excel:"强制修改为无效人数(选填)"`
}

func (*UpdateTeamReadExcel) Configure(rc *exl.ReadConfig) {}

func UpdateTeamUserHandler(ctx iris.Context) {
	//1.解析execl
	_, handle, err := ctx.FormFile("file")
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	file, _ := handle.Open()
	defer file.Close()
	if models, err := exl.Read[*UpdateTeamReadExcel](file); err != nil {
		fmt.Println("read excel err:" + err.Error())
		ctx.JSON(utils.ResponseServerError(errors.New("excel读取错误")))
		return
	} else {
		fmt.Printf("read excel num: %d\n", len(models))
		var teamServe admin.TeamService
		for i, model := range models {
			//从第二行开始读取
			if i == 0 || utils.StringIsEmpty(model.UserID) {
				continue
			}
			teamServe.UpdateTeamUser(model.UserID, model.TeamNumber, model.IsEffectiveManpower, model.IsNotEffectiveManpower)
		}
		ctx.JSON(utils.ResponseOK())
	}
}

type ReadExcelTeamUpdate struct {
	UserId                  string `excel:"团长ID(必填)"`
	UserName                string `excel:"团长姓名(选填)"`
	NickName                string `excel:"团长昵称(选填)"`
	Phone                   string `excel:"团长手机号(选填)"`
	Email                   string `excel:"团长邮箱(选填)"`
	TeamNumber              string `excel:"团队编号(选填)"`
	Month                   string `excel:"修改月份（选填）"`
	MonthEnvoyLevel         string `excel:"修改月份大使等级（选填）"`
	MonthInvitationProgress string `excel:"修改月份邀请进度(选填)"`
	TeamPeopleHistory       string `excel:"修改历史总人数(选填)"`
	TeamIncome              string `excel:"修改团队本月总收入(选填)"`
	Status                  string `excel:"任职状态（0：离职；1：正常；2：删除合并到默认渠道）(必填)"`
	TeamPermissions         string `excel:"团队项目ID资格（不填表示全部项目，可视规则按照项目配置决定；如果填写则表示只能看到填写的项目，可视规则由本表以及项目表共同决定）（选填）"`
}

func (*ReadExcelTeamUpdate) Configure(rc *exl.ReadConfig) {}
func TeamImportUpdateHandler(ctx iris.Context) {
	//1.解析execl
	_, handle, err := ctx.FormFile("file")
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	file, _ := handle.Open()
	defer file.Close()
	if models, err := exl.Read[*ReadExcelTeamUpdate](file); err != nil {
		fmt.Println("read excel err:" + err.Error())
		ctx.JSON(utils.ResponseServerError(errors.New("excel读取错误")))
		return
	} else {
		fmt.Printf("read excel num: %d\n", len(models))
		teams := make([]admindao.SystemTeam, len(models)-1)
		users := make([]admindao.SystemUser, len(models)-1)
		for i, model := range models {
			//从第二行开始读取
			if i == 0 {
				continue
			}
			index := i - 1
			//改team表
			teams[index].UserId = model.UserId
			if utils.StringIsNotEmpty(model.UserName) {
				teams[index].UserName = model.UserName
			}
			if utils.StringIsNotEmpty(model.NickName) {
				teams[index].NickName = model.NickName
			}
			if utils.StringIsNotEmpty(model.TeamNumber) {
				teams[index].TeamNumber = model.TeamNumber
			}
			if utils.StringIsNotEmpty(model.TeamPeopleHistory) {
				if val, err := utils.StringToInt(model.TeamPeopleHistory); err != nil {
					ctx.JSON(utils.ResponseServerError(err))
					return
				} else {
					teams[index].TeamPeopleHistory = val
				}
			}
			if utils.StringIsNotEmpty(model.TeamIncome) {
				if val, err := utils.StringToFloat64(model.TeamIncome); err != nil {
					ctx.JSON(utils.ResponseServerError(err))
					return
				} else {
					teams[index].TeamIncome = val
				}
			}
			if utils.StringIsNotEmpty(model.TeamPermissions) {
				teams[index].TeamPermissions = model.TeamPermissions
			}
			//改user表
			users[index].UserId = model.UserId
			if utils.StringIsNotEmpty(model.Phone) {
				users[index].Phone = model.Phone
			}
			if utils.StringIsNotEmpty(model.Email) {
				users[index].Email = model.Email
			}
		}
		var teamServe admin.TeamService
		if err := teamServe.TeamImportUpdate(teams, users); err != nil {
			ctx.JSON(utils.ResponseServerError(err))
			return
		}
		ctx.JSON(utils.ResponseOK())
		return
	}
}

type TeamPageRequest struct {
	UserName          string `json:"user_name"`
	TeamNumber        string `json:"team_number"`
	UserId            string `json:"user_id"`
	Status            string `json:"status"`
	TeamIncome        string `json:"team_income"`
	Level             string `json:"level"`
	Page              int64  `json:"page" validate:"required"`
	PageSize          int64  `json:"page_size" validate:"required"`
	TeamPeople        uint   `json:"team_people"`
	TeamPeopleHistory uint   `json:"team_people_history"`
}

// QueryTeamPageHandler 查询团队列表
func QueryTeamPageHandler(ctx iris.Context) {
	var RequestParams TeamPageRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var teamServe admin.TeamService
	if total, list, err := teamServe.QueryTeamPage(RequestParams.UserName, RequestParams.TeamNumber, RequestParams.UserId, RequestParams.Status, RequestParams.TeamIncome, RequestParams.Level, RequestParams.Page, RequestParams.PageSize, RequestParams.TeamPeople, RequestParams.TeamPeopleHistory); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(iris.Map{"count": total, "list": list}))
		return
	}
}

type TeamPermissionsRequest struct {
	Id              uint   `json:"id" validate:"required"`
	TeamPermissions string `json:"team_permissions"`
	Status          uint   `json:"status"`
}

// EditTeamInfoHandler 编辑团队信息
func EditTeamInfoHandler(ctx iris.Context) {
	var RequestParams TeamPermissionsRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var teamServe admin.TeamService
	if err := teamServe.EditTeamInfo(RequestParams.Id, RequestParams.Status, RequestParams.TeamPermissions); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseOK())
		return
	}
}

type QueryHistoryPeopleAndLevelRequest struct {
	Id uint `json:"id" validate:"required"`
}

// QueryHistoryPeopleAndLevelHandler 历史月份有效人数与等级
func QueryHistoryPeopleAndLevelHandler(ctx iris.Context) {
	var RequestParams QueryHistoryPeopleAndLevelRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var teamServe admin.TeamService
	if list, err := teamServe.QueryHistoryPeopleAndLevel(RequestParams.Id); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(iris.Map{"list": list}))
		return
	}
}

type QueryTeamInfoRequest struct {
	UserId string `json:"user_id" validate:"required"`
}

// QueryTeamInfoHandler 查询团队详情
func QueryTeamInfoHandler(ctx iris.Context) {
	var RequestParams QueryTeamInfoRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var teamServe admin.TeamService
	//先查是不是团长
	if flag, err := teamServe.QueryUserIsTeamLeader(RequestParams.UserId); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		if flag {
			//是团长则返回团队信息
			if team, err := teamServe.QueryTeamInfo(RequestParams.UserId); err != nil {
				ctx.JSON(utils.ResponseServerError(err))
				return
			} else {
				ctx.JSON(utils.ResponseData(team))
				return
			}
		} else {
			//不是团长返回空
			ctx.JSON(utils.ResponseData(""))
			return
		}
	}
	/*if team, err := teamServe.QueryTeamInfo(RequestParams.UserId); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(team))
		return
	}*/
}

type QueryTeamManagePageRequest struct {
	Id               uint   `json:"id"`
	UserId           string `json:"user_id"`                         //用户ID
	TeamNumber       string `json:"team_number" validate:"required"` //团队编号
	RealName         string `json:"real_name"`                       //姓名
	AmountFrom       string `json:"amount_from"`                     //最后收入芝草从
	AmountTo         string `json:"amount_to"`                       //最后收入芝草到
	BalanceFrom      string `json:"balance_from"`                    //当前剩余芝草从
	BalanceTo        string `json:"balance_to"`                      //当前剩余芝草到
	LastBalanceStart string `json:"last_balance_start"`              //收入日期起
	LastBalanceEnd   string `json:"last_balance_end"`                //收入日期止
	CreatedAtStart   string `json:"created_at_start"`                //入团日期起
	CreatedAtEnd     string `json:"created_at_end"`                  //入团日期止
	Auth             string `json:"auth"`                            //权限
	Page             int64  `json:"page" validate:"required"`
	PageSize         int64  `json:"page_size" validate:"required"`
}

// QueryTeamManagePageHandler 团队管理列表
func QueryTeamManagePageHandler(ctx iris.Context) {
	var RequestParams QueryTeamManagePageRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var teamServe admin.TeamService
	if total, list, err := teamServe.QueryTeamManagePage(RequestParams.UserId, RequestParams.TeamNumber, RequestParams.RealName, RequestParams.LastBalanceStart, RequestParams.LastBalanceEnd, RequestParams.CreatedAtStart, RequestParams.CreatedAtEnd, RequestParams.AmountFrom, RequestParams.AmountTo, RequestParams.BalanceFrom, RequestParams.BalanceTo, RequestParams.Auth, RequestParams.Page, RequestParams.PageSize); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(iris.Map{"count": total, "list": list}))
		return
	}
}

// TeamLevelHandler 查询团队等级设置
func TeamLevelHandler(ctx iris.Context) {
	var dictServe services.SystemDictService
	if data, err := dictServe.GetValueByType(team.ZXZ_TEAM_LEVEL); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(data))
		return
	}
}

type GetTeamIncomeListRequest struct {
	Page       int64  `json:"page" validate:"required"`
	PageSize   int64  `json:"page_size" validate:"required"`
	TeamNumber string `json:"team_number" validate:"required"`
	YearMonth  string `json:"year_month" validate:"required"`
}

func GetTeamIncomeListHandler(ctx iris.Context) {
	var RequestParams GetTeamIncomeListRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var teamServe admin.TeamService
	if total, list, err := teamServe.GetTeamIncomeList(RequestParams.TeamNumber, RequestParams.YearMonth, RequestParams.Page, RequestParams.PageSize); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(iris.Map{"count": total, "list": list}))
		return
	}
}

type GetTeamSumIncomeThisMonthRequest struct {
	TeamNumber string `json:"team_number"`
}

func GetTeamSumIncomeThisMonthHandler(ctx iris.Context) {
	var RequestParams GetTeamSumIncomeThisMonthRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var teamServe admin.TeamService
	if income, err := teamServe.GetTeamSumIncomeThisMonth(RequestParams.TeamNumber); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(income))
		return
	}
}

type ExportTeamMemberIncomeByCountRequest struct {
	TeamNumber      string `json:"team_number" validate:"required"`
	IncomeDateStart string `json:"income_date_start"`
	IncomeDateEnd   string `json:"income_date_end"`
	JoinDateStart   string `json:"join_date_start"`
	JoinDateEnd     string `json:"join_date_end"`
}

func ExportTeamMemberIncomeByCountHandler(ctx iris.Context) {
	var RequestParams ExportTeamMemberIncomeByCountRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var teamServe admin.TeamService
	ExportData, err := teamServe.ExportTeamMemberIncomeByCount(RequestParams.TeamNumber, RequestParams.IncomeDateStart, RequestParams.IncomeDateEnd, RequestParams.JoinDateStart, RequestParams.JoinDateEnd)
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}

	exportFile := excelize.NewFile()
	style, _ := exportFile.NewStyle(&excelize.Style{
		Fill: excelize.Fill{Type: "gradient", Color: []string{"#8ED3F5", "#8ED3F5"}, Shading: 1},
	})
	//创建工作表行数
	var excel = make(map[string][]interface{}, 0)
	//比较表头的长度
	var excelHeader = make(map[string]int, 0)
	titles := []string{"团队用户ID", "团队用户姓名", "团队用户昵称", "团队用户手机号", "团队用户邮箱", "团队用户支付宝", "收入日期",
		"本次收入芝草", "当前剩余芝草", "入团日期", "激活状态", "激活日期", "成员团队权限", "团长用户ID", "团长姓名,",
		"团长昵称", "团长手机号", "团长邮箱", "团队编号", "团队等级"}
	//删除默认工作表
	for _, datum := range ExportData {
		sheetsTitle := titles
		//处理表头
		colNameDefault := generateColName(20)
		var rowsData []interface{}
		rowsData = append(rowsData, datum.UserId)
		rowsData = append(rowsData, datum.RealName)
		rowsData = append(rowsData, datum.NickName)
		rowsData = append(rowsData, datum.Phone)
		rowsData = append(rowsData, datum.Email)
		rowsData = append(rowsData, datum.AlipayAccount)
		rowsData = append(rowsData, datum.IncomeTime.Format(timehandler.FormatLayoutTime))
		rowsData = append(rowsData, datum.Amount)
		rowsData = append(rowsData, datum.RemainAmount)
		rowsData = append(rowsData, datum.JoinTeamDate.Format(timehandler.FormatLayoutTime))
		if datum.IsEffectiveManpower == IS_EFFECTIVE_MANPOWER_FALSE {
			rowsData = append(rowsData, "未激活")
		} else if datum.IsEffectiveManpower == IS_EFFECTIVE_MANPOWER_TRUE {
			rowsData = append(rowsData, "已激活")
		}
		rowsData = append(rowsData, datum.TeamActivationDate)
		rowsData = append(rowsData, "")
		rowsData = append(rowsData, datum.TlUserId)
		rowsData = append(rowsData, datum.TlRealName)
		rowsData = append(rowsData, datum.TlNickName)
		rowsData = append(rowsData, datum.TlPhone)
		rowsData = append(rowsData, datum.TlEmail)
		rowsData = append(rowsData, datum.TeamNumber)
		rowsData = append(rowsData, datum.Level)
		sheet := fmt.Sprintf("团队成员每次收入导出表")
		excel[sheet] = append(excel[sheet], rowsData)
		exportFile.NewSheet(sheet)

		exportFile.SetCellStyle(sheet, "A1", colNameDefault+"1", style)
		//插入表头
		if _, ok := excelHeader[sheet]; ok {
			if excelHeader[sheet] < len(sheetsTitle) {
				exportFile.SetSheetRow(sheet, "A1", &sheetsTitle)
				excelHeader[sheet] = len(sheetsTitle)
			}
		} else {
			exportFile.SetSheetRow(sheet, "A1", &sheetsTitle)
			excelHeader[sheet] = len(sheetsTitle)
		}
		//插入内容
		exportFile.SetSheetRow(sheet, fmt.Sprintf("A+%d", len(excel[sheet])+1), &rowsData)
	}
	exportFile.DeleteSheet("Sheet1")
	unix := time.Now().UnixNano()
	tempFilename := fmt.Sprintf("./export/team_member_income_by_count_%d.xlsx", unix)
	if err := exportFile.SaveAs(tempFilename); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}

	defer exportFile.Close()
	//删除本地临时文件
	defer os.Remove(tempFilename)
	bucketClient := oss.BucketClient{}
	readFile, _ := ioutil.ReadFile(fmt.Sprintf("./export/team_member_income_by_count_%d.xlsx", unix))
	bucketClient.UpBytes(readFile, fmt.Sprintf("task-assign/team/export/team_member_income_by_count_%d.xlsx", unix))
	ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: fmt.Sprintf("%s/task-assign/team/export/team_member_income_by_count_%d.xlsx", utils.ServerConf.AliOssConf.CallBackHost, unix)})
	return
}

func ExportTeamMemberIncomeBySumHandler(ctx iris.Context) {
	var RequestParams ExportTeamMemberIncomeByCountRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var teamServe admin.TeamService
	ExportData, err := teamServe.ExportTeamMemberIncomeBySum(RequestParams.TeamNumber, RequestParams.IncomeDateStart, RequestParams.IncomeDateEnd, RequestParams.JoinDateStart, RequestParams.JoinDateEnd)
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}

	exportFile := excelize.NewFile()
	style, _ := exportFile.NewStyle(&excelize.Style{
		Fill: excelize.Fill{Type: "gradient", Color: []string{"#8ED3F5", "#8ED3F5"}, Shading: 1},
	})
	//创建工作表行数
	var excel = make(map[string][]interface{}, 0)
	//比较表头的长度
	var excelHeader = make(map[string]int, 0)
	titles := []string{"团队用户ID", "团队用户姓名", "团队用户昵称", "团队用户手机号", "团队用户邮箱", "团队用户支付宝",
		"累计收入芝草", "当前剩余芝草", "入团日期", "激活状态", "激活日期", "成员团队权限", "团长用户ID", "团长姓名,",
		"团长昵称", "团长手机号", "团长邮箱", "团队编号", "团队等级"}
	//删除默认工作表
	for _, datum := range ExportData {
		sheetsTitle := titles
		//处理表头
		colNameDefault := generateColName(19)
		var rowsData []interface{}
		rowsData = append(rowsData, datum.UserId)
		rowsData = append(rowsData, datum.RealName)
		rowsData = append(rowsData, datum.NickName)
		rowsData = append(rowsData, datum.Phone)
		rowsData = append(rowsData, datum.Email)
		rowsData = append(rowsData, datum.AlipayAccount)
		rowsData = append(rowsData, datum.Amount)
		rowsData = append(rowsData, datum.RemainAmount)
		rowsData = append(rowsData, datum.JoinTeamDate.Format(timehandler.FormatLayoutTime))
		if datum.IsEffectiveManpower == IS_EFFECTIVE_MANPOWER_FALSE {
			rowsData = append(rowsData, "未激活")
		} else if datum.IsEffectiveManpower == IS_EFFECTIVE_MANPOWER_TRUE {
			rowsData = append(rowsData, "已激活")
		}
		rowsData = append(rowsData, datum.TeamActivationDate)
		rowsData = append(rowsData, "")
		rowsData = append(rowsData, datum.TlUserId)
		rowsData = append(rowsData, datum.TlRealName)
		rowsData = append(rowsData, datum.TlNickName)
		rowsData = append(rowsData, datum.TlPhone)
		rowsData = append(rowsData, datum.TlEmail)
		rowsData = append(rowsData, datum.TeamNumber)
		rowsData = append(rowsData, datum.Level)
		sheet := fmt.Sprintf("团队成员累计收入导出表")
		excel[sheet] = append(excel[sheet], rowsData)
		exportFile.NewSheet(sheet)

		exportFile.SetCellStyle(sheet, "A1", colNameDefault+"1", style)
		//插入表头
		if _, ok := excelHeader[sheet]; ok {
			if excelHeader[sheet] < len(sheetsTitle) {
				exportFile.SetSheetRow(sheet, "A1", &sheetsTitle)
				excelHeader[sheet] = len(sheetsTitle)
			}
		} else {
			exportFile.SetSheetRow(sheet, "A1", &sheetsTitle)
			excelHeader[sheet] = len(sheetsTitle)
		}
		//插入内容
		exportFile.SetSheetRow(sheet, fmt.Sprintf("A+%d", len(excel[sheet])+1), &rowsData)
	}
	exportFile.DeleteSheet("Sheet1")
	unix := time.Now().UnixNano()
	tempFilename := fmt.Sprintf("./export/team_member_income_by_sum_%d.xlsx", unix)
	if err := exportFile.SaveAs(tempFilename); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}

	defer exportFile.Close()
	//删除本地临时文件
	defer os.Remove(tempFilename)
	bucketClient := oss.BucketClient{}
	readFile, _ := ioutil.ReadFile(fmt.Sprintf("./export/team_member_income_by_sum_%d.xlsx", unix))
	bucketClient.UpBytes(readFile, fmt.Sprintf("task-assign/team/export/team_member_income_by_sum_%d.xlsx", unix))
	ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: fmt.Sprintf("%s/task-assign/team/export/team_member_income_by_sum_%d.xlsx", utils.ServerConf.AliOssConf.CallBackHost, unix)})
	return
}

type QuerySystemUserRestrictionRequest struct {
	UserId uint `json:"user_id" validate:"required"`
}

func QuerySystemUserRestrictionHandler(ctx iris.Context) {
	var RequestParams QuerySystemUserRestrictionRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var teamServe admin.TeamService
	if res, err := teamServe.QuerySystemUserRestriction(RequestParams.UserId); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(res))
		return
	}
}

func GetTeamInviteUrlHandler(ctx iris.Context) {
	var teamServe admin.TeamService
	if res, err := teamServe.GetTeamInviteUrl(); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(res))
		return
	}
}

func QueryUserIsTeamLeaderHandler(ctx iris.Context) {
	var claims services.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}

	var userServe admindao.Common[admindao.SystemUser]
	if user, err := userServe.First(map[string]interface{}{"id": claims.Id}); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		var teamServe admindao.Common[admindao.SystemTeam]
		if count, err := teamServe.Count(map[string]interface{}{"user_id": user.UserId}); err != nil {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
			return
		} else {
			if count > 0 {
				ctx.JSON(utils.ResponseData(map[string]interface{}{"flag": true}))
				return
			} else {
				ctx.JSON(utils.ResponseData(map[string]interface{}{"flag": false}))
				return
			}
		}
	}
}

type ExportExcelTeamIncomeSetting struct {
	Index        int     `excel:"序号"`
	ProjectId    string  `excel:"项目ID"`
	Title        string  `excel:"项目名称"`
	IncomeType   int     `excel:"提成形式（1表示基础工资，2表示固定数值）"`
	Level        int     `excel:"团队等级"`
	IncomeNumber float64 `excel:"提成比例（如果填写百分比，则是按照基础工资*百分比发放）（如果填写的是固定数值，则按照固定值*数量发放）"`
}

type IncomeExportRequest struct {
	Ids []uint `json:"ids"`
}

func (*ExportExcelTeamIncomeSetting) Configure(rc *exl.WriteConfig) {}
func IncomeExportHandler(ctx iris.Context) {
	var RequestParams IncomeExportRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	querMap := map[string]interface{}{}
	if len(RequestParams.Ids) > 0 {
		querMap["id"] = RequestParams.Ids
	}
	var serve admindao.Common[admindao.SystemTeamIncomeSetting]
	ExportData, err := serve.FindAll(querMap)
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	index := 0
	exportTeamIncomeRecords := make([]*ExportExcelTeamIncomeSetting, len(ExportData))
	for i, model := range ExportData {
		exportTeamIncomeRecords[index] = &ExportExcelTeamIncomeSetting{}
		exportTeamIncomeRecords[index].Index = i + 1
		exportTeamIncomeRecords[index].ProjectId = model.ProjectId
		exportTeamIncomeRecords[index].Title = model.Title
		exportTeamIncomeRecords[index].IncomeType = model.IncomeType
		exportTeamIncomeRecords[index].Level = model.Level
		exportTeamIncomeRecords[index].IncomeNumber = model.IncomeNumber
		index++
	}
	unix := time.Now().UnixNano()
	if err := exl.Write(fmt.Sprintf("./export/export_team_income_records_%d.xlsx", unix), exportTeamIncomeRecords); err != nil {
		fmt.Println("write excel err:" + err.Error())
		return
	}
	tempFilename := fmt.Sprintf("./export/export_team_income_records_%d.xlsx", unix)
	//删除本地临时文件
	defer os.Remove(tempFilename)
	bucketClient := oss.BucketClient{}
	readFile, _ := ioutil.ReadFile(fmt.Sprintf("./export/export_team_income_records_%d.xlsx", unix))
	bucketClient.UpBytes(readFile, fmt.Sprintf("task-assign/export/export_team_income_records_%d.xlsx", unix))
	ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: fmt.Sprintf("%s/task-assign/export/export_team_income_records_%d.xlsx", utils.ServerConf.AliOssConf.CallBackHost, unix)})
	return
}

type ExportExcelEffectiveNumber struct {
	Level  string `excel:"团队等级"`
	Number int    `excel:"需要的累计有效人数"`
}

func (*ExportExcelEffectiveNumber) Configure(rc *exl.WriteConfig) {}
func ExcelEffectiveNumberExportsHandler(ctx iris.Context) {
	var serve admindao.Common[admindao.SystemDict]
	ExportData, err := serve.FindAll(map[string]interface{}{"dict_type": team.ZXZ_TEAM_LEVEL})
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	index := 0
	exportExcelEffectiveRecords := make([]*ExportExcelEffectiveNumber, len(ExportData))
	for _, model := range ExportData {
		exportExcelEffectiveRecords[index] = &ExportExcelEffectiveNumber{}
		exportExcelEffectiveRecords[index].Level = model.DictValue
		exportExcelEffectiveRecords[index].Number = model.DictNumber
		index++
	}
	unix := time.Now().UnixNano()
	if err := exl.Write(fmt.Sprintf("./export/export_team_effective_number_records_%d.xlsx", unix), exportExcelEffectiveRecords); err != nil {
		fmt.Println("write excel err:" + err.Error())
		return
	}
	tempFilename := fmt.Sprintf("./export/export_team_effective_number_records_%d.xlsx", unix)
	//删除本地临时文件
	defer os.Remove(tempFilename)
	bucketClient := oss.BucketClient{}
	readFile, _ := ioutil.ReadFile(fmt.Sprintf("./export/export_team_effective_number_records_%d.xlsx", unix))
	bucketClient.UpBytes(readFile, fmt.Sprintf("task-assign/export/export_team_effective_number_records_%d.xlsx", unix))
	ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: fmt.Sprintf("%s/task-assign/export/export_team_effective_number_records_%d.xlsx", utils.ServerConf.AliOssConf.CallBackHost, unix)})
	return
}

type ExportTeamInfo struct {
	UserId            string  `excel:"团长用户ID"` //团长用户id
	UserName          string  `excel:"团长姓名"`   //团长用户姓名
	NickName          string  `excel:"团长昵称"`   //团长用户昵称
	TlPhone           string  `excel:"团长手机号"`  //团长手机号
	TlEmail           string  `excel:"团长邮箱"`   //团长邮箱
	TeamNumber        string  `excel:"团队编号"`   //团队编号
	Level             int     `excel:"团队本月等级"` //团队等级
	NowInviteProgress string  `excel:"本月邀请进度"` //本月邀请进度
	NowMonth          string  `excel:"当前月份"`   //当前月份
	LastMonthLevel    string  `excel:"上月团队等级"` //上月团队等级
	PeopleAndLevel    string  `excel:"历史月份有效人数与等级"`
	TeamPeopleHistory int     `excel:"历史有效人数"` //团队历史人数
	TlUrl             string  `excel:"团长专属链接"`
	TeamIncome        float64 `excel:"团队本月总收入芝草"`                   //团队本月收入
	Status            int     `excel:"任职状态（0：离职；1：正常；2：删除合并到默认渠道）"` //0 注销;1 任职中; 2 已离职
	TeamPermissions   string  `excel:"团队项目可见配置"`                    //团队项目可见配置
	//TeamPeople        int     `excel:"team_people"`                 //团队人数
	//NowInvitePeople   int     `excel:"now_invite_people"`           //本月邀请人数
}

type ExportTeamInfoRequest struct {
	Ids []uint `json:"ids"`
}

func (*ExportTeamInfo) Configure(rc *exl.WriteConfig) {}
func ExcelTeamInfoExportsHandler(ctx iris.Context) {
	var RequestParams ExportTeamInfoRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var teamServe admin.TeamService
	ExportData, err := teamServe.ExportTeamInfo(RequestParams.Ids)
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	if res, err := teamServe.GetTeamInviteUrl(); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		exportExcelRecords := make([]*ExportTeamInfo, len(ExportData))
		for i, model := range ExportData {
			exportExcelRecords[i] = &ExportTeamInfo{}
			exportExcelRecords[i].UserId = model.UserId
			exportExcelRecords[i].UserName = model.UserName
			exportExcelRecords[i].NickName = model.NickName
			exportExcelRecords[i].TlPhone = model.TlPhone
			exportExcelRecords[i].TlEmail = model.TlEmail
			exportExcelRecords[i].TeamNumber = model.TeamNumber
			exportExcelRecords[i].Level = model.Level
			exportExcelRecords[i].NowInviteProgress = model.NowInviteProgress
			exportExcelRecords[i].NowMonth = model.NowMonth
			exportExcelRecords[i].LastMonthLevel = model.LastMonthLevel
			exportExcelRecords[i].PeopleAndLevel = model.PeopleAndLevel
			exportExcelRecords[i].TeamPeopleHistory = model.TeamPeopleHistory
			//exportExcelRecords[i].TlUrl = model.TlUrl
			exportExcelRecords[i].TlUrl = res.DictValue + model.TeamNumber
			exportExcelRecords[i].TeamIncome = model.TeamIncome
			exportExcelRecords[i].Status = model.Status
			exportExcelRecords[i].TeamPermissions = model.TeamPermissions
		}
		unix := time.Now().UnixNano()
		if err := exl.Write(fmt.Sprintf("./export/export_team_info_records_%d.xlsx", unix), exportExcelRecords); err != nil {
			fmt.Println("write excel err:" + err.Error())
			return
		}
		tempFilename := fmt.Sprintf("./export/export_team_info_records_%d.xlsx", unix)
		//删除本地临时文件
		defer os.Remove(tempFilename)
		bucketClient := oss.BucketClient{}
		readFile, _ := ioutil.ReadFile(fmt.Sprintf("./export/export_team_info_records_%d.xlsx", unix))
		bucketClient.UpBytes(readFile, fmt.Sprintf("task-assign/export/export_team_info_records_%d.xlsx", unix))
		ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: fmt.Sprintf("%s/task-assign/export/export_team_info_records_%d.xlsx", utils.ServerConf.AliOssConf.CallBackHost, unix)})
		return
	}
}

type ExcelTeamInfoModify struct {
	TeamNumber      string `excel:"团队编号(必填)"`
	Status          int    `excel:"任职状态（0：离职；1：正常；2：删除合并到默认渠道）(必填)"`
	TeamPermissions string `excel:"团队项目ID资格（不填表示全部项目，可视规则按照项目配置决定；如果填写则表示只能看到填写的项目，可视规则由本表以及项目表共同决定）（选填）"`
}

func (*ExcelTeamInfoModify) Configure(rc *exl.ReadConfig) {}
func ExcelTeamInfoModifyHandler(ctx iris.Context) {
	//1.解析execl
	_, handle, err := ctx.FormFile("file")
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	file, _ := handle.Open()
	defer file.Close()
	if models, err := exl.Read[*ExcelTeamInfoModify](file); err != nil {
		fmt.Println("read excel err:" + err.Error())
		ctx.JSON(utils.ResponseServerError(errors.New("excel读取错误")))
		return
	} else {
		fmt.Printf("read excel num: %d\n", len(models))
		teams := make([]admindao.SystemTeam, len(models)-1)
		for i, model := range models {
			//从第二行开始读取
			if i == 0 {
				continue
			}
			index := i - 1
			//改team表
			if utils.StringIsNotEmpty(model.TeamNumber) {
				teams[index].TeamNumber = model.TeamNumber
			}
			teams[index].Status = model.Status
			if utils.StringIsNotEmpty(model.TeamPermissions) {
				teams[index].TeamPermissions = model.TeamPermissions
			} else {
				teams[index].TeamPermissions = ""
			}
		}
		var teamServe admin.TeamService
		if err := teamServe.ExcelTeamInfoModify(teams); err != nil {
			ctx.JSON(utils.ResponseServerError(err))
			return
		}
		ctx.JSON(utils.ResponseOK())
		return
	}
}

type ExcelTeamHistoryLevelModify struct {
	TeamNumber string `excel:"团队编号(必填)"`
	Month      string `excel:"修改月份（必填）"`
	Level      int    `excel:"修改对应月份的团队等级（必填）（只能修改历史月份等级，不能修改当月的）"`
}

func (*ExcelTeamHistoryLevelModify) Configure(rc *exl.ReadConfig) {}
func ExcelTeamHistoryLevelModifyHandler(ctx iris.Context) {
	//1.解析execl
	_, handle, err := ctx.FormFile("file")
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	file, _ := handle.Open()
	defer file.Close()
	if models, err := exl.Read[*ExcelTeamHistoryLevelModify](file); err != nil {
		fmt.Println("read excel err:" + err.Error())
		ctx.JSON(utils.ResponseServerError(errors.New("excel读取错误")))
		return
	} else {
		fmt.Printf("read excel num: %d\n", len(models))
		_db := mysql.GetDB()
		err := _db.Transaction(func(tx *gorm.DB) error {
			var teamDao admindao.Common[admindao.SystemTeamHistory]
			teamDao.Tx = tx
			for _, team := range models {
				var teamHistory admindao.SystemTeamHistory
				teamHistory.TeamNumber = team.TeamNumber
				teamHistory.Level = team.Level
				if err := tx.Model(&admindao.SystemTeamHistory{}).Where("left(created_at,7) = ? and team_number = ?", team.Month, team.TeamNumber).Update("level", team.Level).Error; err != nil {
					return err
				}
			}
			return nil
		})
		if err != nil {
			ctx.JSON(utils.ResponseServerError(err))
			return
		}

		ctx.JSON(utils.ResponseOK())
		return
	}
}
